using EasyXaf.LowCode.WorkflowEditors.Models.Activities;
using EasyXaf.LowCode.WorkflowEditors.UndoManagers;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using System.Collections.Specialized;
using System.ComponentModel;

namespace EasyXaf.LowCode.WorkflowEditors.Nodes;

public partial class BranchesNode : IDisposable
{
    private bool IsReadOnly
    {
        get => WorkflowMode >= WorkflowMode.Debug;
    }

    private bool VisibleAddAction
    {
        get
        {
            if (BranchesActivity is DecisionActivity)
            {
                return false;
            }
            return true;
        }
    }

    [CascadingParameter]
    public IUndoManager UndoManager { get; set; }

    [CascadingParameter]
    public WorkflowMode WorkflowMode { get; set; }

    [Parameter]
    public IBranchesActivity BranchesActivity { get; set; }

    [Parameter]
    public EventCallback<MouseEventArgs> AddActivityClicked { get; set; }

    [Parameter]
    public EventCallback<MouseEventArgs> AddBranchClicked { get; set; }

    private string GetBranchNodeClassNames(IBranch branch)
    {
        var classNames = new List<string>
        {
            "branch-node"
        };

        if (BranchesActivity.Branches.FirstOrDefault() == branch)
        {
            classNames.Add("first-branch-node");
        }

        if (BranchesActivity.Branches.LastOrDefault() == branch)
        {
            classNames.Add("last-branch-node");
        }

        return string.Join(" ", classNames);
    }

    private void CollapseBranches()
    {
        UndoManager.ChangeActivityCollapseState(BranchesActivity, !BranchesActivity.IsCollapse);
    }

    private void BranchesActivity_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (WorkflowMode == WorkflowMode.Outline)
        {
            InvokeAsync(StateHasChanged);
        }
    }

    private void Branches_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        InvokeAsync(StateHasChanged);
    }

    protected override void OnInitialized()
    {
        base.OnInitialized();

        BranchesActivity.PropertyChanged += BranchesActivity_PropertyChanged;
        BranchesActivity.Branches.CollectionChanged += Branches_CollectionChanged;
    }

    public void Dispose()
    {
        BranchesActivity.PropertyChanged -= BranchesActivity_PropertyChanged;
        BranchesActivity.Branches.CollectionChanged -= Branches_CollectionChanged;

        GC.SuppressFinalize(this);
    }
}